package com.itheima.user.controller;

import com.itheima.user.entity.OrderEntity;
import com.itheima.user.entity.UserEntity;
import com.itheima.user.service.UserService;
import com.itheima.user.vo.request.AddOrderVO;
import com.itheima.user.vo.response.OrderResultVO;
import com.itheima.user.vo.response.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //用户登录
    @GetMapping("/login/{userName}/{password}")
    public ResultVO login(@PathVariable("userName") String userName, @PathVariable("password") String password) {
        boolean loginResult = userService.login(userName, password);
        ResultVO result = new ResultVO();
        if (loginResult) {
            result.setSuccess(true);
        } else {
            result.setSuccess(false);
        }
        return result;
    }

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    //查询用户订单信息
    @GetMapping("/findUserOrders/{userId}")
    public OrderResultVO findUserOrders(@PathVariable("userId") Integer userId) {

        OrderResultVO orderResultVO = new OrderResultVO();
        UserEntity userEntity = userService.findUserById(userId);

//        String url = "http://localhost:9001/order/findOrderInfoByUserId/" + userId;

        //todo
//        List<ServiceInstance> instances = discoveryClient.getInstances("ORDER-SERVICE");
//        ServiceInstance serviceInstance = instances.get(0);
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();
//        String url = "http://" + host + ":" + port + "/order/findOrderInfoByUserId/" + userId;


        String url = "http://order-service/order/findOrderInfoByUserId/" + userId;

        List<OrderEntity> objectList = restTemplate.getForObject(url, List.class);
        orderResultVO.setUserName(userEntity.getUserName());
        orderResultVO.setOrderList(objectList);

        return orderResultVO;
    }

    //添加订单
    @PostMapping("/addUserOrder")
    public ResultVO addUserOrder(@RequestBody AddOrderVO addOrderVO) {
        ResultVO result = new ResultVO();
        //判断用户是否存在
        UserEntity userEntity = userService.findUserById(addOrderVO.getUserId());
        if (userEntity == null) {
            result.setSuccess(false);
            return result;
        }

        //todo

        return result;
    }
}
